package com.szxydb.dmp.admin.system.service.impl;

import com.szxydb.dmp.admin.system.model.ValidateCode;
import com.szxydb.dmp.admin.system.service.ValidateCodeService;
import com.szxydb.dmp.constants.Constants;
import com.szxydb.dmp.exception.CrmebException;
import com.szxydb.dmp.utils.CrmbUtil;
import com.szxydb.dmp.utils.RedisUtil;
import com.szxydb.dmp.utils.ValidateCodeUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取验证码信息
     * @return
     */
    @Override
    public ValidateCode get() {
        ValidateCodeUtil.Validate randomCode = ValidateCodeUtil.getRandomCode();
        if (randomCode == null){
            return null;
        }
        String value = randomCode.getValue().toLowerCase();
        String md5Key = DigestUtils.md5Hex(value);
        String redisKey = getRedisKey(md5Key);
        redisUtil.set(redisKey,value,5L, TimeUnit.MINUTES);
        String base64Str = randomCode.getBase64Str();
        return new ValidateCode(md5Key, CrmbUtil.getBase64Image(base64Str));
    }

    /**
     * 获取redis key
     * @param md5Key
     * @return
     */
    public String getRedisKey(String md5Key){
        return Constants.VALIDATE_REDIS_KEY_PREFIX+md5Key;
    }

    /**
     * 验证
     * @param validateCode
     * @return
     */
    @Override
    public boolean check(ValidateCode validateCode) {
        if (!redisUtil.exists(getRedisKey(validateCode.getKey()))) throw new CrmebException("验证码错误");
        Object redisValue = redisUtil.get(getRedisKey(validateCode.getKey()));
        if (!redisValue.equals(validateCode.getCode())){
            return false;
        }
        return true;
    }
}
